package com.col.flutterplugin.float_button_overlay;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.NotificationManager;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.col.flutterplugin.float_button_overlay.services.FloatButtonService;
//import io.flutter.plugin.common.MethodCall;
//import io.flutter.plugin.common.MethodChannel;
//import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
//import io.flutter.plugin.common.MethodChannel.Result;
//import io.flutter.plugin.common.PluginRegistry.Registrar;
//import static com.col.flutterplugin.float_button_overlay.utils.Constants.CHANNEL;
import static com.col.flutterplugin.float_button_overlay.utils.Constants.TAG;

import java.util.List;

/**
 * FloatButtonOverlayPlugin
 */
public class FloatButtonOverlayPlugin extends Activity  {

    private Context mContext;
    @SuppressLint("StaticFieldLeak")
    private static Activity mActivity;
    public static int ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE = 1237;
    private static NotificationManager notificationManager;
    private FloatButtonService mService;

    public static void invokeCallBack(String type, Object params) {

    }


    public static void openOverlay(Context mContext,String packageName,String activityName){
        Log.d(TAG, "Will show FloatButton");
        Intent i = new Intent(mContext, FloatButtonService.class);

        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        i.putExtra("packageName", packageName);
        i.putExtra("activityName", activityName);
        i.putExtra("showOverlay",true);
        mContext.startService(i);
    }
    public static void openOverlay(Context mContext,String packageName,String activityName,int ballSize){
        Log.d(TAG, "Will show FloatButton");
        Intent i = new Intent(mContext, FloatButtonService.class);

        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        i.putExtra("packageName", packageName);
        i.putExtra("activityName", activityName);
        i.putExtra("showOverlay",true);
        i.putExtra("floatBallSize",ballSize);
        mContext.startService(i);
    }

    public static void closeOverlay(Context mContext,String packageName,String activityName){
        final Intent i = new Intent(mContext, FloatButtonService.class);
        Log.d(TAG, "Stopping service");
//            mContext.stopService(i);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        i.putExtra("packageName", packageName);
        i.putExtra("activityName", activityName);
        i.putExtra("showOverlay",false);
        mContext.startService(i);
    }


    public static void startAppActivity(Context context ,String packageName,String activityName){
        Intent intent = new Intent();
        ComponentName componentName =new ComponentName(packageName,activityName);
        intent.setComponent(componentName);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static boolean checkPermissions(Context mContext){
        return checkPermission(mContext);
    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE) {
            if (!Settings.canDrawOverlays(mContext)) {
                Log.e(TAG, "Float Button Overlay will not work without 'Can Draw Over Other Apps' permission");
                Toast.makeText(mContext, "Float Button Overlay will not work without 'Can Draw Over Other Apps' permission", Toast.LENGTH_LONG).show();
            }
        }

    }

    public static boolean checkPermission(Context mContext) {
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.Q) {
//            initNotificationManager(mContext);
//            if (!notificationManager.areBubblesAllowed()) {
//                Log.e(TAG, "System Alert Window will not work without enabling the android bubbles");
//                Toast.makeText(mContext, "System Alert Window will not work without enabling the android bubbles", Toast.LENGTH_LONG).show();
//            } else {
//                //TODO to check for higher android versions, post their release
//                Log.d(TAG, "Android bubbles are enabled");
//                return true;
//            }
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(mContext)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + mContext.getPackageName()));
                if (mActivity == null) {
                    if (mContext != null) {
                        mContext.startActivity(intent);
                        Toast.makeText(mContext, "Please grant, Can Draw Over Other Apps permission.", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "Can't detect the permission change, as the mActivity is null");
                    } else {
                        Log.e(TAG, "'Can Draw Over Other Apps' permission is not granted");
                        Toast.makeText(mContext, "Can Draw Over Other Apps permission is required. Please grant it from the app settings", Toast.LENGTH_LONG).show();
                    }
                } else {
                    mActivity.startActivityForResult(intent, ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
                }
            } else {
                return true;
            }
        }
        return true;
    }

    @SuppressWarnings("unused")
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private boolean handleBubblesPermissionForAndroidQ() {
        int devOptions = Settings.Secure.getInt(mContext.getContentResolver(), Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);
        if (devOptions == 1) {
            Log.d(TAG, "Android bubbles are enabled");
            return true;
        } else {
            Log.e(TAG, "System Alert Window will not work without enabling the android bubbles");
            Toast.makeText(mContext, "Enable android bubbles in the developer options, for System Alert Window to work", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private static void initNotificationManager(Context mContext) {
        if (notificationManager == null) {
            if (mContext == null) {
                if (mActivity != null) {
                    mContext = mActivity.getApplicationContext();
                }
            }
            if (mContext == null) {
                Log.e(TAG, "Context is null. Can't show the System Alert Window");
                return;
            }
            notificationManager = mContext.getSystemService(NotificationManager.class);
        }
    }

    public static boolean isPackageAvailable(Context context,String packageName){
        final PackageManager packageManager = context.getPackageManager();

        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        for ( int i = 0; i < pinfo.size(); i++ )
        {

            // 循环判断是否存在指定包名
            if(pinfo.get(i).packageName.equalsIgnoreCase(packageName)){
                return true;
            }

        }
        return false;
    }

}
